package com.shuai.user.service.inner;

import cn.hutool.json.JSONUtil;
import com.shuai.common.constant.UserConstant;
import com.shuai.common.service.user.InnerUserService;
import com.shuai.user.domain.entity.User;
import com.shuai.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@DubboService
@Slf4j
public class InnerUserServiceImpl implements InnerUserService {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void decreaseUserToken(int tokenNum, String userId) {
        userService.decreaseUserToken(tokenNum, userId);
        String userJson = stringRedisTemplate.opsForValue().get(UserConstant.USER_ATTRIBUTE_REDIS_KEY + userId);
        User user = JSONUtil.toBean(userJson, User.class);
        user.setResidueToken(user.getResidueToken() - tokenNum);
        stringRedisTemplate.opsForValue().set(UserConstant.USER_ATTRIBUTE_REDIS_KEY + userId, JSONUtil.toJsonStr(user));
    }
}
